<template>
  <div>
    <a-form-model
      id="components-form-demo-normal-login"
      :model="model"
      ref="form"
      class="register-form"
      @keyup.enter.native="handleSubmit"
      :rules="validatorRules"
    >
      <a-form-model-item required prop="companyCode">
        <a-input
          v-model="model.companyCode"
          size="large"
          placeholder="请输入企业编码"
        >
          <a-icon
            slot="prefix"
            type="user"
            :style="{ color: 'rgba(0,0,0,.25)' }"
          />
        </a-input>
        <a-tooltip placement="top">
          <template slot="title">
            <span style="font-size: 12px"
              >企业编码是企业在后羿零碳的唯一标识，一企业一码永久保存。因为手机号因企业人员工作流动会很可能发生变更或调整，企业编码对比手机号具备更好的永久保存性。
              <br />1、后羿零碳登录、找回密码均需要填写企业编码，建议设置企业编码尽量简洁，便于记忆，方便填写
              <br />
              2、
              企业编码在后羿零碳具备唯一性，不能与其他企业编码重复，系统会自动校验唯一性</span
            >
          </template>
          <span class="code_">企业编码是什么</span>
        </a-tooltip>
      </a-form-model-item>
      <a-form-model-item required prop="userName">
        <a-input
          v-model="model.userName"
          size="large"
          type="text"
          autocomplete="false"
          placeholder="请输入用户名"
        >
          <a-icon
            slot="prefix"
            type="lock"
            :style="{ color: 'rgba(0,0,0,.25)' }"
          />
        </a-input>
      </a-form-model-item>
      <a-form-model-item required prop="phone">
        <a-input
          v-model="model.phone"
          size="large"
          type="phone"
          autocomplete="false"
          placeholder="请输入手机号"
        >
          <a-icon
            slot="prefix"
            type="lock"
            :style="{ color: 'rgba(0,0,0,.25)' }"
          />
        </a-input>
      </a-form-model-item>
      <a-row :gutter="0">
        <a-col :span="17">
          <a-form-model-item required prop="verification">
            <a-input
              v-model="model.verification"
              size="large"
              type="text"
              placeholder="请输入验证码"
            >
              <a-icon
                slot="prefix"
                type="smile"
                :style="{ color: 'rgba(0,0,0,.25)' }"
              />
            </a-input>
          </a-form-model-item>
        </a-col>
        <a-col
          :offset="1"
          :span="6"
          style="text-align: right"
          class="code"
          :class="[sendMsgDisabled ? 'code_click' : 'code_normal']"
          @click="getCode()"
        >
          <div v-if="!sendMsgDisabled">获取验证码</div>
          <div v-else>{{ time + "秒后获取" }}</div>
        </a-col>
      </a-row>
      <a-form-model-item prop="password">
        <a-input
          v-model="model.password"
          size="large"
          type="password"
          autocomplete="false"
          placeholder="登录密码"
        >
          <a-icon
            slot="prefix"
            type="lock"
            :style="{ color: 'rgba(0,0,0,.25)' }"
          />
        </a-input>
      </a-form-model-item>
      <a-form-model-item required prop="confirmpassword">
        <a-input
          v-model="model.confirmpassword"
          size="large"
          type="password"
          autocomplete="false"
          placeholder="重复登录密码"
        >
          <a-icon
            slot="prefix"
            type="lock"
            :style="{ color: 'rgba(0,0,0,.25)' }"
          />
        </a-input>
      </a-form-model-item>
      <a-form-model-item>
        <a-checkbox @change="handleRememberMeChange" default-checked
          >我已阅读并同意 <a href=""> 《用户协议》 </a>及<a href="">
            《后羿零碳隐私声明》</a
          ></a-checkbox
        >

        <!-- <div @click="handleChangeCheckCode">刷新验证码</div> -->
        <a-button
          type="primary"
          @click.stop.prevent="handleSubmit"
          class="login-form-button"
        >
          下一步
        </a-button>

        <a
          @click="
            () => {
              $router.push('/login');
            }
          "
        >
          返回登录
        </a>
      </a-form-model-item>
    </a-form-model>
  </div>
</template>

<script>
import { duplicateCheck } from "@/api/api";
import { getAction, postAction } from "@/api/manage";
import bus from "@/bus";
export default {
  name: "registerAccount",
  data() {
    return {
      model: {
        companyCode: "code1",
        userName: "test",
        verification: 111111,
        phone: 13333141732,
        password: "abc123456.",
        confirmpassword: "abc123456.",
      },
      validatorRules: {
        companyCode: [
          { required: true, message: "请输入企业编码!" },
          { validator: this.validateCompanyCode },
        ],
        userName: [{ required: true, message: "请输入用户账号!" }],
        phone: [
          { required: true, message: "请输入手机号!" },
          { validator: this.validatePhone },
        ],
        password: [
          {
            required: true,
            pattern:
              /^(?=.*[a-zA-Z])(?=.*\d)(?=.*[~!@#$%^&*()_+`\-={}:";'<>?,./]).{8,}$/,
            message: "密码由8位数字、大小写字母和特殊符号组成!",
          },
          { validator: this.validateToNextPassword, trigger: "change" },
        ],
        confirmpassword: [
          { required: true, message: "请重新输入登录密码!" },
          { validator: this.compareToFirstPassword },
        ],
        verification: [
          {
            required: true,
            message: "请输入验证码!",
          },
        ],
      },
      time: 60, // 发送验证码倒计时
      sendMsgDisabled: false,
    };
  },
  methods: {
    // 登录事件
    handleSubmit(e) {
      //   this.handleLogin();
      this.$refs["form"].validate((success) => {
        if (success) {
          let register = this.model;
          //   console.log(register);
          postAction("/sys/regist/account", register).then((res) => {
            //   console.log(res);
            if (!res.success) {
              this.registerFailed(res.message);
            } else {
              //   console.log(this.model, 333);
              bus.$emit("next", this.model);
              // this.$router.push({
              //   name: "registerResult",
              //   params: { ...values },
              // });
            }
          });
        }
      });
    },
    getCode() {
      this.validateFields(["phone"], (err) => {
        if (!err) {
          const that = this;
          that.sendMsgDisabled = true;
          const interval = window.setInterval(function () {
            if (that.time-- <= 0) {
              that.time = 60;
              that.sendMsgDisabled = false;
              window.clearInterval(interval);
            }
          }, 1000);
        }
      });
    },

    validateUsername(rule, value, callback) {
      var params = {
        tableName: "sys_user",
        fieldName: "userName",
        fieldVal: value,
        dataId: this.userId,
      };
      duplicateCheck(params).then((res) => {
        if (res.success) {
          callback();
        } else {
          callback("用户名已存在!");
        }
      });
    },
    validateCompanyCode(rule, value, callback) {
      if (!value) {
        callback();
      } else {
          var params = {
            tableName: "hylt_base_company",
            fieldName: "company_code",
            fieldVal: value,
          };
          duplicateCheck(params).then((res) => {
            if (res.success) {
              callback();
            } else {
              callback("企业编码已经存在,请重新输入!");
            }
          });
      }
    },
    validatePhone(rule, value, callback) {
      if (!value) {
        callback();
      } else {
        if (new RegExp(/^1[3|4|5|7|8|9][0-9]\d{8}$/).test(value)) {
          callback();
          //   var params = {
          //     tableName: "sys_user",
          //     fieldName: "phone",
          //     fieldVal: value,
          //     dataId: this.userId,
          //   };
          //   duplicateCheck(params).then((res) => {
          //     if (res.success) {
          //       callback();
          //     } else {
          //       callback("手机号已存在!");
          //     }
          //   });
        } else {
          callback("请输入正确格式的手机号码!");
        }
      }
    },
    validateToNextPassword(rule, value, callback) {
      const confirmpassword = this.model.confirmpassword;
      if (value && confirmpassword && value !== confirmpassword) {
        callback("两次输入的密码不一样！");
      }
      if (value && this.confirmDirty) {
        this.$refs.form.validateField(["confirmpassword"]);
      }
      callback();
    },
    compareToFirstPassword(rule, value, callback) {
      if (value && value !== this.model.password) {
        callback("两次输入的密码不一样！");
      } else {
        callback();
      }
    },
    /**
     * 验证字段
     * @param arr
     * @param callback
     */
    validateFields(arr, callback) {
      let promiseArray = [];
      for (let item of arr) {
        let p = new Promise((resolve, reject) => {
          this.$refs["form"].validateField(item, (err) => {
            if (!err) {
              resolve();
            } else {
              reject(err);
            }
          });
        });
        promiseArray.push(p);
      }
      Promise.all(promiseArray)
        .then(() => {
          callback();
        })
        .catch((err) => {
          callback(err);
        });
    },
    handleRememberMeChange(e) {
      this.rememberMe = e.target.checked;
    },
  },
};
</script>

<style lang="scss">
.register-form {
  min-width: 500px;
  padding: 0 40px;
  .code_ {
    position: absolute;
    right: -90px;
    top: -3px;
    cursor: pointer;
    color: #0c67ee;
    font-size: 12px;
  }
}
</style>